package com.gack.helper.redis;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisClient {
	@Autowired
	private JedisPool jedisPool;

	private final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 目前用途 : 获取订单号 , 如果能获取到, 则为重复提交
	 * 
	 * @param key
	 * @return
	 */
	public synchronized String get(String key) {
		Jedis jedis = jedisPool.getResource();
		String str = null;
		try {
			str = jedis.get(key);
		} catch (Exception e) {
			log.error(e.toString());
		}finally {
			try {
				jedis.close();
			} catch (Exception e) {
				log.error(e.toString());
			}
		}
		return str;
	}

	public synchronized String set(String key, String value) {
		Jedis jedis = jedisPool.getResource();
		String str = null;
		try {
			str = jedis.set(key, value);
		} catch (Exception e) {
			log.error(e.toString());
		}finally {
			try {
				jedis.close();
			} catch (Exception e) {
				log.error(e.toString());
			}
		}
		return str;
	}
	
	/**
	 * 仅当key 不存在时,才添加成功
	 * 设置成功，返回 1 。
	 *设置失败，返回 0 。
	 * @param key
	 * @param value
	 * @return
	 */
	public synchronized  Long setNx(String key, String value) {
		Jedis jedis = jedisPool.getResource();
		Long str = null;
		try {
			str = jedis.setnx(key, value);
		} finally {
			try {
				jedis.close();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.toString());
			}
		}
		return str;
	}
/**
 * 移除 某个key  成功 返回 1 
 * @param key
 * @return
 */
	public synchronized Long remove(String key) {
		Jedis jedis = jedisPool.getResource();
		Long str = null;
		try {
			str = jedis.del(key);
		}
		catch (Exception e) {
			log.error(e.toString());
		}finally {
			try {
				jedis.close();
			} catch (Exception e) {
				log.error(e.toString());
			}
		}
		return str;
		
	}
	/**
	 * 设置 过期时间的存入redis
	 * 
	 * @param key
	 * @param seconds秒
	 * @param value
	 * @return
	 */
	public synchronized String setex(String key, int seconds, String value) {
		Jedis jedis = jedisPool.getResource();
		String str = null;
		try {
			str = jedis.setex(key, seconds, value);
		} catch (Exception e) {
			log.error(e.toString());
		}finally {
			try {
				jedis.close();
			} catch (Exception e) {
				log.error(e.toString());
			}
		}
		return str;
	}
	
}
